package client.ui.view;

import client.Main;
import client.UserState;
import client.assets.Icons;
import client.control.Controller;
import client.control.ResponseEntity;
import client.entity.User;
import client.ui.component.button.FlatButton;
import client.ui.component.button.MaterialButton;
import client.ui.component.layout.VFlowLayout;
import client.ui.component.navigation.Navigation;
import client.ui.component.navigation.NavigationBarGroup;
import client.ui.component.navigation.NavigationBarItem;
import client.ui.view.base.PanelControl;
import client.ui.view.dialogview.ChangePasswordDialog;
import client.ui.view.dialogview.LoginDialog;
import client.ui.theme.ThisFont;
import client.ui.util.MaterialColors;
import client.ui.view.base.FrameBase;
import client.ui.view.panel.main.CartPanel;
import client.ui.view.panel.main.ChatPanel;
import client.ui.view.panel.main.GoodsPanel;
import client.ui.view.panel.main.MyDataPanel;
import com.alibaba.fastjson.JSONObject;
import util.CacheUtil;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class MainPage extends FrameBase implements ActionListener,WindowListener{
    private Executor singleThreadExecutor = Executors.newSingleThreadExecutor();
    private JPopupMenu popupMenu = new JPopupMenu();
    private String username = "";
    private Navigation navigation;
    private JPanel userPanel;
    private CardLayout cardLayout = new CardLayout();
    private JPanel contentPanel;
    public MainPage(){
        super();
        this.setTitle("物品闲置购物平台");
        this.setIconImage(Icons.shop.getImage());
        initial();
    }

    protected void initial(){
        if (UserState.isLogin()){
            this.username = UserState.getUsername();
        }
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel userPanel = getUserPanel();
        JPanel navigatorBar = getNavigatorBar();
        contentPanel = getContentPanel();
        JPanel menuPanel = getMenuPanel();

        navigation = new Navigation(navigatorBar, contentPanel, menuPanel, userPanel);
        this.setContentPane(navigation);
        //判断是否已经登录，如果登录则查询网络获取并更新用户信息
        if (UserState.isLogin()){
            updatePanel("userPanel");
        }
    }

    private JPanel getUserPanel(){
        BorderLayout borderLayout = new BorderLayout();
        borderLayout.setHgap(0);
        borderLayout.setVgap(0);
        userPanel = new JPanel(borderLayout);
        JLabel headImage = new JLabel(Icons.head_image,SwingConstants.CENTER);
        headImage.setBorder(null);
        headImage.setMinimumSize(new Dimension(150,150));
        headImage.setMaximumSize(new Dimension(150,150));
        headImage.setName("headImage");
        JLabel userName = new JLabel(username,SwingConstants.CENTER);
        userName.setName("username");
        userName.setFont(ThisFont.LARGE_BOLD_FONT);
        userName.setForeground(MaterialColors.WHITE);
        userName.setToolTipText(userName.getText());
        userName.setBorder(new EmptyBorder(0,0,4,0));
        userPanel.add(headImage, BorderLayout.CENTER);
        userPanel.add(userName, BorderLayout.SOUTH);

        //设置头像的监听，建立右键菜单
        JPopupMenu popupMenu = new JPopupMenu();
        JMenuItem changeHeadImage = new JMenuItem("更换头像",null);
        JMenuItem changeUsername = new JMenuItem("更改用户名");
        JMenuItem logout = new JMenuItem("退出登录");
        JMenuItem changePassword = new JMenuItem("修改密码");
        changeHeadImage.setActionCommand("changeHeadImage");
        changeHeadImage.addActionListener(this);
        changeUsername.setActionCommand("changeUsername");
        changeUsername.addActionListener(this);
        changePassword.setActionCommand("changePassword");
        changePassword.addActionListener(this);
        logout.setActionCommand("logout");
        logout.addActionListener(this);
        popupMenu.add(changeHeadImage);
        popupMenu.add(changeUsername);
        popupMenu.add(changePassword);
        popupMenu.add(logout);
        if (UserState.isLogin()){
            userPanel.setComponentPopupMenu(popupMenu);
        } else {
            userPanel.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    LoginDialog.showLoginDialog(MainPage.this, MainPage.this);
                }
            });
        }
        return userPanel;
    }

    private JPanel getNavigatorBar(){
        VFlowLayout flowLayout = new VFlowLayout(VFlowLayout.TOP);
        flowLayout.setHorizontalFill(true);
        flowLayout.setHgap(0);
        flowLayout.setVgap(0);
        JPanel navigatorBar = new JPanel(flowLayout);
        //商品列表
        NavigationBarGroup navigationBarGroup = new NavigationBarGroup();
        NavigationBarItem goodList = new NavigationBarItem("商品列表",null, navigationBarGroup);
        goodList.setActionCommand("goodList");
        goodList.addActionListener(this);
        //购物车
        NavigationBarItem cartList = new NavigationBarItem("购物车",null, navigationBarGroup);
        cartList.setActionCommand("cartList");
        cartList.addActionListener(this);
        //聊天列表
        NavigationBarItem chatList = new NavigationBarItem("聊天列表",null, navigationBarGroup);
        chatList.setActionCommand("chatList");
        chatList.addActionListener(this);
        //我的个人标签
        NavigationBarItem my = new NavigationBarItem("我的",null,navigationBarGroup);
        my.setActionCommand("my");
        my.addActionListener(this);

        goodList.setPreferredSize(new Dimension(200, 40));
        cartList.setPreferredSize(new Dimension(200,40));
        chatList.setPreferredSize(new Dimension(200,40));
        my.setPreferredSize(new Dimension(200,40));

        navigatorBar.add(goodList);
        navigatorBar.add(cartList);
        navigatorBar.add(chatList);
        navigatorBar.add(my);

        goodList.setSelected(true);
        return navigatorBar;
    }

    private JPanel getMenuPanel(){
        JPanel menuPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton setting = getMenuButton(Icons.setting);
        JButton about = getMenuButton(Icons.about);
        JButton logout = getMenuButton(Icons.exit);
        menuPanel.add(setting);
        menuPanel.add(about);
        menuPanel.add(logout);

        //设置的监听
        setting.setActionCommand("setting");
        setting.addActionListener(this);
        //设置关于的监听
        about.setActionCommand("about");
        about.addActionListener(this);
        //设置退出的监听
        logout.setActionCommand("logout");
        logout.addActionListener(this);
        return menuPanel;
    }

    private JButton getMenuButton(ImageIcon imageIcon){
        FlatButton button = new FlatButton("",imageIcon);
        button.setBorder(new EmptyBorder(0,12,0,12));
        return button;
    }

    private JPanel getContentPanel(){
        JPanel contentPanel = new JPanel(cardLayout);
        JPanel goodsPanel = new GoodsPanel();
        JPanel cartPanel = new CartPanel();
        JPanel chatPanel = new ChatPanel();
        JPanel myDataPanel = new MyDataPanel();
        contentPanel.add("goods",goodsPanel);
        contentPanel.add("cart",cartPanel);
        contentPanel.add("chat",chatPanel);
        contentPanel.add("my",myDataPanel);
        return contentPanel;
    }

    /**
     * @Description 根据面板名称更新面板数据,内部开设线程更新UI外部调用不需要开设线程，造成资源浪费
     * @param panelName 面板名称，可更新的有userPanel
     * @author 孔明浩
     * @Date 2020/4/3
     */
    @Override
    public void updatePanel(String panelName){
        if ("userPanel".equals(panelName)) {
            singleThreadExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    ResponseEntity responseEntity = Controller.USER_CONTROL.getUserInfo(UserState.getToken());
                    UserState.setUser(JSONObject.parseObject(responseEntity.getData(), User.class));
                    if (responseEntity.getCode() == 0) {
                        final ImageIcon imageIcon = Controller.USER_CONTROL.getHeadImage(UserState.getToken(), 150);
                        SwingUtilities.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                                ((JLabel) userPanel.getComponent(0)).setIcon(imageIcon);
                                ((JLabel) userPanel.getComponent(1)).setText(UserState.getUsername());
                            }
                        });
                    }

                }
            });
        }
    }

    @Override
    public void setSize(int width, int height) {
        super.setSize(width, height);
        navigation.setSize(width,height);
        setMinimumSize(new Dimension(400,600));
    }

    /**
      * @Description 通过点击事件带的命令执行对应操作
      * @param e 点击事件
      * @author 孔明浩
      * @Date 2020/4/4
      */
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(e.getActionCommand());
        //根据获取的命令执行相应的操作
        switch (e.getActionCommand()){
            case "changeHeadImage":
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileFilter(new FileNameExtensionFilter(
                        "图片文件(*.jpg,*.jpeg,*.png, *.gif)","jpg","jpeg", "png", "gif"));
                fileChooser.showOpenDialog(this);
                File file = fileChooser.getSelectedFile();
                if (file != null){
                    singleThreadExecutor.execute(new Runnable() {
                        @Override
                        public void run() {
                            ResponseEntity responseEntity = Controller.USER_CONTROL.setHeadPic(UserState.getToken(), file);
                            if (responseEntity.getCode() == 0){
                                updatePanel("userPanel");
                            }
                        }
                    });
                }
                break;
            case "changeUsername":
                String newName = JOptionPane.showInputDialog(this,"输入想要更改的用户名");
                //判断获取字符串
                if (newName != null && newName.length() > 0){
                    singleThreadExecutor.execute(new Runnable() {
                        //通过网络更新用户名
                        @Override
                        public void run() {
                            ResponseEntity responseEntity = Controller.USER_CONTROL.setUserInfo(UserState.getToken(), newName);
                            if (responseEntity.getCode() == 0){
                                updatePanel("userPanel");
                                UserState.setUsername(newName);
                            }
                        }
                    });
                }
                break;
            case "logout":
                int result = JOptionPane.showConfirmDialog(MainPage.this,
                        "确认退出账户",
                        "退出账户",
                        JOptionPane.YES_NO_CANCEL_OPTION);
                if (result == JOptionPane.YES_OPTION){
                    UserState.logout();
                    result = JOptionPane.showConfirmDialog(MainPage.this,
                            "是否清除个人数据",
                            "清除数据",
                            JOptionPane.YES_NO_CANCEL_OPTION
                    );
                    if (result == JOptionPane.YES_OPTION){
                        CacheUtil.deleteCache(UserState.getUser().getUserId(),0);
                    }
                    FrameBase.frameBaseList.clear();
                    PanelControl.panels.clear();
                    MainPage.this.dispose();
                    Main.main(null);
                }
                break;
            case "about":
                JOptionPane.showMessageDialog(MainPage.this,
                        "制作人：郭常瑞&孔明浩\nUI:孔明浩\n数据支持：郭常瑞\n");
                break;
            case "my":
                if (UserState.isLogin()){
                    cardLayout.show(contentPanel,"my");
                } else {
                    LoginDialog.showLoginDialog(MainPage.this,MainPage.this);
                }
                break;
            case "goodList":
                cardLayout.show(contentPanel,"goods");
                break;
            case "cartList":
                if (UserState.isLogin()){
                    cardLayout.show(contentPanel,"cart");
                } else {
                    LoginDialog.showLoginDialog(MainPage.this,MainPage.this);
                }
                break;
            case "chatList":
                if (UserState.isLogin()){
                    cardLayout.show(contentPanel,"chat");
                } else {
                    LoginDialog.showLoginDialog(MainPage.this,MainPage.this);
                }
                break;
            case "setting":
                MaterialButton deleteAccount = MaterialButton.BlueButton("彻底删除账户",null);
                deleteAccount.addActionListener(this);
                deleteAccount.setActionCommand("deleteAccount");
                MaterialButton deleteChatData = MaterialButton.BlueButton("清除聊天数据", null);
                deleteChatData.addActionListener(this);
                deleteChatData.setActionCommand("deleteChatData");
                MaterialButton changePassword = MaterialButton.BlueButton("修改密码" ,null);
                changePassword.setActionCommand("changePassword");
                changePassword.addActionListener(this);
                JButton[] buttons = new JButton[3];
                buttons[0] = deleteAccount;
                buttons[1] = changePassword;
                buttons[2] = deleteChatData;
                JOptionPane.showOptionDialog(this,"系统设置","设置",
                        JOptionPane.DEFAULT_OPTION,JOptionPane.PLAIN_MESSAGE,Icons.setting,buttons,0
                        );
                break;
            case "deleteAccount":
                int code = JOptionPane.showConfirmDialog(this,
                        "删除账户操作不可逆转\n删除账户您将会丢失所有数据并且不可恢复",
                        "警告:删除账户", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
                if (code == JOptionPane.YES_OPTION){
                    code = JOptionPane.showConfirmDialog(this,
                            "请再次确认,此操作不可逆转",
                            "警告:正在尝试彻底删除账户", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
                    if (code == 0){
                        UserState.logout();
                        singleThreadExecutor.execute(new Runnable() {
                            @Override
                            public void run() {
                                Controller.USER_CONTROL.deleteAccount(UserState.getToken());
                            }
                        });
                        FrameBase.frameBaseList.clear();
                        PanelControl.panels.clear();
                        this.dispose();
                        Main.main(null);
                    }
                }
                break;
            case "deleteChatData":
                int code1 = JOptionPane.showConfirmDialog(this,
                        "确认删除所有聊天记录",
                        "删除聊天记录", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
                if (code1 == JOptionPane.YES_OPTION){
                    while (true){
                        if (UserState.getId() != null){
                            CacheUtil.deleteCache(UserState.getId(), 0);
                            FrameBase.frameBaseList.clear();
                            PanelControl.panels.clear();
                            this.dispose();
                            Main.main(null);
                            break;
                        }
                    }
                }
                break;
            case "changePassword":
                ChangePasswordDialog.showRegisterDialog(this,this);
                break;
        }
        popupMenu.setVisible(false);
    }

    @Override
    public void windowClosed(WindowEvent e) {
        Controller.CHAT_CONTROL.closeSocket();
    }
}